package com.med.meddataintegrator.jwt.config;


import com.med.meddataintegrator.jwt.filter.JwtFilter;
import com.med.meddataintegrator.jwt.handle.RestAuthenticationFailureHandler;
import com.med.meddataintegrator.jwt.handle.RestAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * //@EnableGlobalMethodSecurity(prePostEnabled = true) //开启方法级别的 权限认证
 *  此处转移到admin模块去开启 因为 admin模块中已经配置了全局的权限认证
 *  此处的配置只是处理 身份认证的过滤器
 */
@Configuration
public class JwtAuthenticationSecurityConfig  extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    /**
     * 装配到Spring Sercurity中的位置中去
     */


    // 自定义的用于处理身份验证成功的处理器
    @Autowired
    private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
    // 自定义的用于处理身份验证失败的处理器
    @Autowired
    private RestAuthenticationFailureHandler restAuthenticationFailureHandler;

    // 密码加密器
    @Autowired
    private PasswordEncoder passwordEncoder;

    // 用户详情服务
    @Autowired
    private UserDetailsService userDetailService;


    @Override
    public void configure(HttpSecurity http) throws Exception {
//        JwtFilter jwtFilter = new JwtFilter();
        JwtFilter jwtFilter = new JwtFilter();
        // 将认证失败处理器和认证成功处理器注入到过滤器中
        jwtFilter.setAuthenticationFailureHandler(restAuthenticationFailureHandler);
        jwtFilter.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler);
        // 并且将认证管理器注入到过滤器中 因为该过滤器返回的是一个AuthenticationManager对象 需要在认证管理器中进行认证逻辑的实现
        jwtFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));


        // 身份验证提供者 并且装上信息
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userDetailService); //将从数据库中查到的用户详情服务注入到其中
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder); //并且将密码加密器注入到其中




        //将校验提供者 加入到HttpSecurity 中
        http.authenticationProvider(daoAuthenticationProvider);
        // 将这个过滤器添加到 UsernamePasswordAuthenticationFilter 之前执
        http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);

    }

}
